let isDOMReady = false;
let isOnload = false;
const cycleFreq = 100;

export const addEventListener = (name, callback, useCapture) => {
    if (window.addEventListener) {
        return window.addEventListener(name, callback, useCapture);
    } else if (window.attachEvent) {
        return window.attachEvent('on' + name, callback);
    }
};

export const onload = (callback) => {
    let timer = null;

    if (document.readyState === 'complete') {
        runCheck();
    } else {
        addEventListener('load', function () {
            runCheck();
        }, false);
    }

    function runCheck() {
        if (performance.timing.loadEventEnd) {
            clearTimeout(timer);
            callback();
            isOnload = true;
        } else {
            timer = setTimeout(runCheck, cycleFreq);
        }
    }
};

export const domReady = (callback) => {
    if (isOnload === true) {
        return;
    }
    let timer = null;

    if (document.readyState === 'interactive') {
        runCheck();
    } else if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', function () {
            runCheck();
        }, false);
    } else if (document.attachEvent) {
        document.attachEvent('onreadystatechange', function () {
            runCheck();
        });
    }

    function runCheck() {
        if (performance.timing.domInteractive) {
            clearTimeout(timer);
            callback();
            isDOMReady = true;
        } else {
            timer = setTimeout(runCheck, cycleFreq);
        }
    }
};
